package com.eightbears.beboy.ui.user.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.eightbears.beboy.R;
import com.eightbears.beboy.adapter.HomeListAdapter;
import com.eightbears.beboy.base.BaseActivity;
import com.eightbears.beboy.base.cache.FriendsCache;
import com.eightbears.beboy.base.util.ErrorUtils;
import com.eightbears.beboy.base.util.GsonUtil;
import com.eightbears.beboy.base.util.InputMethodUtils;
import com.eightbears.beboy.base.util.SPUtil;
import com.eightbears.beboy.base.util.SharesUtil;
import com.eightbears.beboy.base.util.ShowToast;
import com.eightbears.beboy.base.util.okhttp.OkHttpUtils;
import com.eightbears.beboy.base.util.okhttp.callback.StringCallback;
import com.eightbears.beboy.base.view.SwipeBackLayout;
import com.eightbears.beboy.base.view.image.ui.ImageViewActivity;
import com.eightbears.beboy.base.view.image.view.ImageItem;
import com.eightbears.beboy.base.view.image.view.ImagePicker;
import com.eightbears.beboy.base.view.layout.MyLinearLayoutManager;
import com.eightbears.beboy.base.view.popupwindow.MultipeSelectionPopup;
import com.eightbears.beboy.entity.CommonEntity;
import com.eightbears.beboy.entity.HomeListEntity;
import com.eightbears.beboy.entity.UserEntity;
import com.eightbears.beboy.entity.status.Status_Error;
import com.eightbears.beboy.ui.chat.ui.activity.ChatActivity;
import com.eightbears.greendao.Friends;
import com.eightbears.greendao.SearchKey;
import com.hyphenate.chat.EMClient;
import com.socks.library.KLog;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

import static com.eightbears.beboy.base.util.CommonAPI.CONNECTION_STATUS_SUCCESS;
import static com.eightbears.beboy.base.util.CommonAPI.KEY_HTTP_HEADER;
import static com.eightbears.beboy.base.util.CommonAPI.PARAMS_PAGE_SIZE;
import static com.eightbears.beboy.base.util.CommonAPI.URL_BLACKLIST;
import static com.eightbears.beboy.base.util.CommonAPI.URL_FAV_UNFAV;
import static com.eightbears.beboy.base.util.CommonAPI.URL_FOLLOW_UNFOLLOW;
import static com.eightbears.beboy.base.util.CommonAPI.URL_INVITATION;
import static com.eightbears.beboy.base.util.CommonAPI.URL_POST_LIKE;
import static com.eightbears.beboy.base.util.CommonAPI.URL_REPOT;
import static com.eightbears.beboy.base.util.CommonAPI.delayMillis;
import static com.eightbears.beboy.ui.user.activity.SearchPostActivity.PARAMS_SEARCH_KEY;
import static com.eightbears.beboy.ui.user.activity.UserInfoActivity.PARAMS_USER_INFO;
import static com.eightbears.beboy.ui.user.fragment.HomeFragment.PARAMS_BUY_POST;
import static com.eightbears.beboy.ui.user.fragment.HomeFragment.PARAMS_POST_ID;
import static com.eightbears.beboy.ui.user.fragment.HomeFragment.PARAMS_REQUEST_TYPE_KEY;

/**
 * 主页搜索结果页面
 */
public class SearchPostListActivity extends BaseActivity implements
        BaseQuickAdapter.RequestLoadMoreListener, SwipeRefreshLayout.OnRefreshListener {

    @BindView(R.id.rv_list)
    RecyclerView rv_list;
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout swipeLayout;
    @BindView(R.id.sw_finish)
    SwipeBackLayout sw_finish;
    @BindView(R.id.tv_title)
    TextView tv_title;

    private SearchKey searchKey;
    private HomeListAdapter homeListAdapter;
    private MultipeSelectionPopup multipeSelectionPopup;
    private HomeListEntity.Post post;
    private UserEntity mUserEntity;
    private Friends friends;

    private int page = 1;
    private int isEnd = 0;
    private boolean isErr = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_post_list);

        initView();
        initData();
        initEvent();
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        tv_title.setText("搜索结果");
        initAdapter();
    }

    @Override
    protected void initData() {
        searchKey = (SearchKey) getIntent().getExtras().get(PARAMS_SEARCH_KEY);
        mUserEntity = SPUtil.getUser();
        if (null != searchKey) {
            getData();
        }
    }

    @Override
    protected void initEvent() {
        sw_finish.setCallBack(new SwipeBackLayout.CallBack() {
            @Override
            public void onFinish() {
                InputMethodUtils.hindInputMethod(getApplication());
                finish();
            }
        });

        //查看图片
        homeListAdapter.setOnImageClickListener(new HomeListAdapter.OnClickImageItemListener() {
            @Override
            public void onImageClick(BaseQuickAdapter baseViewHolder, View view, int i) {
                Intent intentPreview = new Intent(SearchPostListActivity.this, ImageViewActivity.class);
                intentPreview.putExtra(ImagePicker.EXTRA_IMAGE_ITEMS, (ArrayList<ImageItem>) baseViewHolder.getData());
                intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, i);
                startActivity(intentPreview);
                overridePendingTransition(R.anim.slide_right_in, R.anim.slide_left_out);
            }
        });

        // 购买帖子
        homeListAdapter.setOnByContentClickListener(new HomeListAdapter.OnByContentClickListener() {
            @Override
            public void onByClick(BaseQuickAdapter baseQuickAdapter, View view, int i, String type) {
                HomeListEntity.Post post = (HomeListEntity.Post) baseQuickAdapter.getData().get(i);
                switch (type) {
                    case HomeListAdapter.STATUS_BUY_CONTENT:
                        startLocalActivity(SearchPostListActivity.this, PaymentActivity.class, PARAMS_BUY_POST, post);
                        break;
                    case HomeListAdapter.STATUS_SHOW_CONTENT:
                        startLocalActivity(SearchPostListActivity.this, PostDetailActivity.class, PARAMS_POST_ID, post.getId());
                        break;
                }

            }
        });

        homeListAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {

            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                post = (HomeListEntity.Post) adapter.getData().get(position);
                switch (view.getId()) {
                    case R.id.ll_btn_like:  // 点赞
                        executeLike();
                        break;
                    case R.id.ll_btn_share:  // 分享
                        SharesUtil.shareContent(SearchPostListActivity.this, post.getId());
                        break;
                    case R.id.ll_follow_drop_down:  // 下拉菜单
                        dropDownMenu();
                        break;
                    case R.id.iv_user_head:
                        startLocalActivity(SearchPostListActivity.this, UserInfoActivity.class,
                                PARAMS_USER_INFO, post.getUser_id());
                        break;
                }
            }
        });
    }

    //初始化适配器
    private void initAdapter() {
        swipeLayout.setOnRefreshListener(this);
        swipeLayout.setColorSchemeColors(getResources().getColor(R.color.text_select_color),
                getResources().getColor(R.color.text_select_color),
                getResources().getColor(R.color.text_select_color),
                getResources().getColor(R.color.text_select_color));
        rv_list.setLayoutManager(new MyLinearLayoutManager(this));
        homeListAdapter = new HomeListAdapter(this);
        homeListAdapter.openLoadAnimation();
        homeListAdapter.setOnLoadMoreListener(this);
        rv_list.setAdapter(homeListAdapter);
    }

    private void getData() {
        swipeLayout.setRefreshing(true);
        OkHttpUtils.get().url(URL_INVITATION)
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .addParams("page", String.valueOf(page))
                .addParams("size", String.valueOf(PARAMS_PAGE_SIZE))
                .addParams("type", PARAMS_REQUEST_TYPE_KEY + "")
                .addParams("keyword", searchKey.getSearch_title())
                .build().execute(new StringCallback() {
            @Override
            public void onResponse(String response) {
                swipeLayout.setRefreshing(false);
                HomeListEntity homeListEntity = GsonUtil.fromJson(response, HomeListEntity.class);
                if (CONNECTION_STATUS_SUCCESS.equals(homeListEntity.getStatus_code())) {
                    isEnd = homeListEntity.getData().getIs_end();
                    if (page == 1)
                        homeListAdapter.setNewData(homeListEntity.getData().getList());
                    else {
                        homeListAdapter.addData(homeListEntity.getData().getList());
                        homeListAdapter.loadMoreComplete();
                    }
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                KLog.e(e.getMessage());
                swipeLayout.setRefreshing(false);
                isErr = false;
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(SearchPostListActivity.this, status_error);
            }
        });
    }

    @OnClick(R.id.ll_back)
    void back() {
        InputMethodUtils.hindInputMethod(this);
        finish();
    }

    /**
     * 点赞
     */
    private void executeLike() {
        post.executeLike();
        homeListAdapter.notifyDataSetChanged();
        String url = URL_POST_LIKE + "/" + post.getStatistic().getPost_id() + "/praise";
        OkHttpUtils.post().url(url)
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .build().execute(new StringCallback() {
            @Override
            public void onResponse(String response) {
                CommonEntity commonEntity = GsonUtil.fromJson(response, CommonEntity.class);
                if (commonEntity.getStatus_code().equals(CONNECTION_STATUS_SUCCESS)) {
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                post.executeLike();
                homeListAdapter.notifyDataSetChanged();
                swipeLayout.setRefreshing(false);
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(SearchPostListActivity.this, status_error);
            }
        });
    }

    /**
     * 关注用户
     */
    private void executeFollow() {
        swipeLayout.setRefreshing(true);
        String url = URL_FOLLOW_UNFOLLOW + post.getUser_id();
        OkHttpUtils.post().url(url)
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .build().execute(new StringCallback() {
            @Override
            public void onResponse(String response) {
                swipeLayout.setRefreshing(false);
                CommonEntity commonEntity = GsonUtil.fromJson(response, CommonEntity.class);
                if (commonEntity.getStatus_code().equals(CONNECTION_STATUS_SUCCESS)) {
                    post.setIs_follow(commonEntity.getData().getStatus());
                    multipeSelectionPopup.dismiss();
                    ShowToast.showShortToast(getString(R.string.text_follow_success));
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                swipeLayout.setRefreshing(false);
                multipeSelectionPopup.dismiss();
                isErr = false;
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(SearchPostListActivity.this, status_error);
            }
        });
    }

    /**
     * 收藏
     */
    private void executeFav() {
        swipeLayout.setRefreshing(true);
        String url = URL_FAV_UNFAV + post.getId() + "/fav";
        OkHttpUtils.post().url(url)
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .build().execute(new StringCallback() {
            @Override
            public void onResponse(String response) {
                swipeLayout.setRefreshing(false);
                CommonEntity commonEntity = GsonUtil.fromJson(response, CommonEntity.class);
                if (commonEntity.getStatus_code().equals(CONNECTION_STATUS_SUCCESS)) {
                    post.setFav(commonEntity.getData().getStatus());
                    multipeSelectionPopup.dismiss();
                    ShowToast.showShortToast(getString(R.string.text_fav_success));
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                swipeLayout.setRefreshing(false);
                multipeSelectionPopup.dismiss();
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(SearchPostListActivity.this, status_error);
            }
        });
    }

    // 添加好友
    private void addFriend() {
        multipeSelectionPopup.dismiss();
        if (mUserEntity.getData().getUser_id() == post.getUser_id()) {
            ShowToast.showShortToast(getString(R.string.not_add_myself));
            return;
        }
        if (friends == null) {
            new Thread(new Runnable() {
                public void run() {
                    try {
                        //demo use a hardcode reason here, you need let user to input if you like
                        String s = getResources().getString(R.string.Add_a_friend);
                        EMClient.getInstance().contactManager().addContact(post.getUser_id() + "", s);
                        runOnUiThread(new Runnable() {
                            public void run() {
                                String s1 = getResources().getString(R.string.send_successful);
                                ShowToast.showShortToast(s1);
                            }
                        });
                    } catch (final Exception e) {
                        runOnUiThread(new Runnable() {
                            public void run() {
                                String s2 = getResources().getString(R.string.Request_add_buddy_failure);
                                ShowToast.showShortToast(s2);
                            }
                        });
                    }
                }
            }).start();
        } else {
            startActivity(new Intent(SearchPostListActivity.this, ChatActivity.class).putExtra("userId", post.getUser_id() + ""));
        }
    }

    /**
     * 拉黑
     */
    private void executeBlack() {
        multipeSelectionPopup.dismiss();
        String url = URL_BLACKLIST + "/" + post.getUser_id();
        OkHttpUtils.post().url(url)
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .build().execute(new StringCallback() {

            @Override
            public void onResponse(String response) {
                ShowToast.showShortToast(getString(R.string.text_add_black_list_success));
                homeListAdapter.getData().remove(post);
                homeListAdapter.notifyDataSetChanged();
            }

            @Override
            public void onError(Call call, Exception e) {
                swipeLayout.setRefreshing(false);
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(SearchPostListActivity.this, status_error);
            }
        });
    }

    /**
     * 删除帖子
     */
    private void cancleReport() {
        multipeSelectionPopup.dismiss();
        String url = URL_REPOT + post.getId() + "/disable";
        OkHttpUtils.put().url(url)
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .build().execute(new StringCallback() {

            @Override
            public void onResponse(String response) {
                ShowToast.showShortToast(getString(R.string.text_post_delete_success));
                homeListAdapter.getData().remove(post);
                homeListAdapter.notifyDataSetChanged();
            }

            @Override
            public void onError(Call call, Exception e) {
                swipeLayout.setRefreshing(false);
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(SearchPostListActivity.this, status_error);
            }
        });
    }


    /**
     * 举报
     */
    private void executeReport() {
        multipeSelectionPopup.dismiss();
        String url = URL_REPOT + post.getId() + "/report";
        OkHttpUtils.post().url(url)
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .build().execute(new StringCallback() {

            @Override
            public void onResponse(String response) {
                ShowToast.showShortToast(getString(R.string.text_report_success));
            }

            @Override
            public void onError(Call call, Exception e) {
                swipeLayout.setRefreshing(false);
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(SearchPostListActivity.this, status_error);
            }
        });
    }

    /**
     * 菜单
     */
    private void dropDownMenu() {
        friends = FriendsCache.getInstance(SearchPostListActivity.this).getCacheById(post.getUser_id());
        String followText = post.getIs_follow() == 1 ? getString(R.string.text_unfollow) : getString(R.string.text_follow);
        String collectText = post.getFav() == 1 ? getString(R.string.text_remove_fav) : getString(R.string.text_fav);
        String addFriendText = friends == null ? getString(R.string.add_friend) : getString(R.string.text_start_chat);

        if (null == multipeSelectionPopup) {
            multipeSelectionPopup = new MultipeSelectionPopup(SearchPostListActivity.this);
            multipeSelectionPopup.setOnClickItemListener(new MultipeSelectionPopup.OnClicktemListener() {
                @Override
                public void onClickItem(View v) {
                    switch (v.getId()) {
                        case R.id.ll_1:
                            executeFollow();
                            break;
                        case R.id.ll_2:
                            executeFav();
                            break;
                        case R.id.ll_3:
                            addFriend();
                            break;
                        case R.id.ll_4:
                            executeBlack();
                            break;
                        case R.id.ll_5:
                            executeReport();
                            break;
                        case R.id.ll_6:
                            cancleReport();
                            break;
                    }
                }
            });
        }
        if (post.getUser_id().equals(mUserEntity.getData().getUser_id())) {
            multipeSelectionPopup.setTx_6Text(getString(R.string.text_delete));
        } else {
            multipeSelectionPopup.setTx_1Text(followText);//关注
            multipeSelectionPopup.setTx_2Text(collectText);//收藏
            multipeSelectionPopup.setTx_3Text(addFriendText);//加好友
            multipeSelectionPopup.setTx_4Text(getString(R.string.Move_into_the_blacklist_new));//加入黑名单
            multipeSelectionPopup.setTx_5Text(getString(R.string.text_report));//举报
        }
        multipeSelectionPopup.showPopupWindow();
    }



    @Override
    public void onRefresh() {
        homeListAdapter.setEnableLoadMore(false);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                isErr = true;
                page = 1;
                homeListAdapter.getData().clear();
                getData();
                homeListAdapter.setEnableLoadMore(true);
            }
        }, delayMillis);
    }

    @Override
    public void onLoadMoreRequested() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (isEnd == 1) {
                    homeListAdapter.loadMoreEnd(true);
                } else {
                    if (isErr) {
                        page++;
                        getData();
                    } else {
                        isErr = true;
                        Toast.makeText(SearchPostListActivity.this, R.string.network_anomalies, Toast.LENGTH_LONG).show();
                        homeListAdapter.loadMoreFail();
                    }
                }
            }
        }, delayMillis);
    }
}
